package org.icy.core.message;

import java.util.ArrayList;

import org.ice.logger.Logger;

public class Subject {
	
	private static Subject instance;

	private ArrayList<Class<? extends Observer>> observers = new ArrayList<Class<? extends Observer>>();
	
	private Subject() {
		
	}
	
	public static Subject getInstance() {
		if (instance == null)
			instance = new Subject();
		return instance;
	}
	
	public void register(Class<? extends Observer> observer)	{
		if (!observers.contains(observer))	{
			observers.add(observer);
		}
	}
	
	public void notifyMessage(String message, Object data) {
		for(Class<? extends Observer> cls: observers)	{
			try {
				Object obj = cls.newInstance();
				if (obj instanceof Observer)	{
					((Observer)obj).onMessage(message, data);
				}
			} catch (Exception ex) {
				Logger.getLogger().log("Error while notifying message: "+ex.toString(), Logger.LEVEL_NOTICE);
			}
		}
	}
}
